import ampub from 'ampub';
import fa from 'fa';
import { ajax, cardCache, toast } from 'nc-lightapp-front';
import { getUsufructAssetTab } from '.';
import constants from '../../constants';
import { addTransitypeBtns } from '../../utils';
import { setBodyBtnsEnable } from './setStatus';


const {
	components: { AMTooltip, LoginContext: { loginContext, getContext, loginContextKeys } },
	utils: { msgUtils: { showMessage }, cardUtils: { createOprationColumn }, multiLangUtils: { getMultiLangByID } }
} = ampub;

const {
	fa_components: {
		CardLinkToBillUtil: { CardLinkToBill },
		ReferFilter: { addHeadAreaReferFilter, addBodyReferFilter }
	},
	fa_utils: { metaUtil: { getAreaItemFields } }
} = fa;

const {
    URL,
	SAMEHEADS,
	templateDataSource,
	assetDataSource,
	FIELDS,
	CARD_BTNS,
	UISTATE,
	BTN_AREA,
	AREA: {
		CARD: {
			ASSET_ALL: assetAll,
			BASIC_INFO_AREA: basicInfoForm,
			FINANCE_AREA: financeForm,
			HEAD_OTHERAREA: headOtherForm,
			USEDEPT_TAB: usedept_tab,
			LRZX_TAB: lrzx_tab,
			ALTER_TAB: alter_tab,
			EVALUATE_TAB: evaluate_tab,
			REDUCE_TAB: reduce_tab,
			DEVALUE_TAB: devalue_tab,
			DEPLOY_TAB: deploy_tab,
			DEP_TAB: dep_tab,
			SUBEQUIP_TAB: subequip_tab,
			LEASE_CHANGE_TAB: lease_change_tab,
			STEPRENTSTANDARD_TAB: steprentstandard_tab,
            RENTPAYPLAN_TAB: rentpayplan_tab,
            DEPACCRUAL_TAB_MONTH: depaccrual_tab_month,
            LOGCHANGERECORD_TAB: logchangerecord_tab,
			USUFRUCTASSET_AREA: usufructasset_tab,
            ASSET_ALL: assetAllArea,
            USUFRUCTASSET_AREA: usufructassetForm
		}
	}
} = constants;

//加载模板
export default function(props) {
	const that = this;
	const { props: { getUrlParam, getSearchParam } } = that;

	const promise = new Promise((resolve, reject) => {
		//从地址栏获取交易类型
		const transiType = getUrlParam('transiType');
		const pagecodeFromUrl = getUrlParam('pagecode') || getSearchParam('p'); //获取pagecode
		if (!transiType && !pagecodeFromUrl) {
			reject();
			return;
		}
		const pagecode = transiType || pagecodeFromUrl;
		that.state.pageCode = pagecode;
		if (that.curr_transiType === transiType) {
			resolve();
			return;
		} else {
			//判断缓存中是否存在
			let templateCached = cardCache.getDefData(transiType, templateDataSource);
			if (templateCached) {
				let { button, meta } = templateCached;
				button = JSON.parse(button);
				meta = JSON.parse(meta);
                mock(meta);
                
				props.button.setButtons(button);
				props.button.hideButtonsByAreas(BTN_AREA.CARD_HEAD);
				modifierMeta.call(that, props, meta);
				initUI(that, meta);
				that.curr_transiType = transiType;
				that.templateid = meta.pageid;
				resolve();
				return;
			}
		}

		props.createUIDom(
			{
				pagecode //页面id
			},
			function(data) {
				if (data) {
					let metaCopy = {};
					if (data.context) {
						// 初始化上下文变量
						loginContext(data.context, assetDataSource);

						//初始化时获取后台数据源信息，并存在缓存中，用于卡片解锁
						getContext(loginContextKeys.dataSourceCode, assetDataSource);
					}
					if (data.button) {
						let button = data.button;
						//获取当前语种
						let currentLangSeq = getContext(loginContextKeys.languageIndex, assetDataSource);
						addTransitypeBtns.call(that, button, currentLangSeq);
						metaCopy.button = JSON.stringify(button);
						props.button.setButtons(button, () => {});
						props.button.hideButtonsByAreas(BTN_AREA.CARD_HEAD);
					}
					if (data.template) {
						let meta = data.template;
                        mock(meta);
						that.templateid = meta.pageid;
						metaCopy.meta = JSON.stringify(meta);
						modifierMeta.call(that, props, meta);
						initUI(that, meta);
					}

					//缓存模板
					cardCache.setDefData(transiType, templateDataSource, metaCopy);
					that.curr_transiType = transiType;
					resolve();
				} else {
					reject();
				}
			}
		);
	});
	return promise;
}

/**
 * 虚构模板，没有使用权license
 * @param {模板} meta 
 */
function mock(meta){
    if(!meta[usufructasset_tab]){
        meta[usufructasset_tab] = {items:[]};
    }
    if(!meta[lease_change_tab]){
        meta[lease_change_tab] = {items:[]};
    }
    if(!meta[steprentstandard_tab]){
        meta[steprentstandard_tab] = {items:[]};
    }
    if(!meta[rentpayplan_tab]){
        meta[rentpayplan_tab] = {items:[]};
    }
    if(!meta[depaccrual_tab_month]){
        meta[depaccrual_tab_month] = {items:[]};
    }
    if(!meta[logchangerecord_tab]){
        meta[logchangerecord_tab] = {items:[]};
        // showMessage(null, { content: "您的模板太旧，请复制预制H1-开头的模板！", color: 'warning' });
    }
}

//获取到 template 后初始化UI
function initUI(that, meta) {
	const { props: { button, getUrlParam, cardTable } } = that;
	//默认显示浏览态按钮
	const { CARD_BROWER_BTNS: browseBtns, CARD_EDIT_BTNS: editBtns, TabsHideDefault } = constants;
	button.setButtonVisible(browseBtns, true);
	button.setButtonVisible(editBtns, false);

	that.props.meta.setMeta(meta, () => {
		//获取各个区域的字段
		that.basicInfoFields = getAreaItemFields(that.props, basicInfoForm); //基本信息区域字段
		that.financeFields = getAreaItemFields(that.props, financeForm); //财务区域字段
		that.financeFields = that.financeFields.concat(FIELDS.ACCOUNT_FIELD);

		initState.call(that, meta);

		//默认收起的页签
		cardTable.toggleCardTable(TabsHideDefault, false);

		//初始化缓存
		let pk2ClientKeyMap = cardCache.getDefData(constants.pk2ClientKeyMap, assetDataSource);
		if (!pk2ClientKeyMap) {
			cardCache.setDefData(constants.pk2ClientKeyMap, assetDataSource, {});
		}

		//从模板上获取可修订的字段
		let reviseFieldsFromTemplet = new Set();
		meta[basicInfoForm].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
		});
		meta[financeForm].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
		});

		// 使用权页签字段集合，排除和表头相同的pk
		let usufructasset_tab_fields = new Set();
		meta[usufructasset_tab].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
			if (!SAMEHEADS.includes(item.attrcode)) {
				usufructasset_tab_fields.add(item.attrcode);
			}
		});
		that.usufructasset_tab_fields = usufructasset_tab_fields;

		meta[headOtherForm].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
		});

		/* 先获取所有可修订的字段，然后过滤出有权限修改的字段集合 */
		that.reviseFields = [ ...reviseFieldsFromTemplet ].filter((f) => {
			return FIELDS.REVISE_FIELDS.includes(f) || f.startsWith(FIELDS.DEF_FIELD) || f.startsWith(FIELDS.UDEF_FIELD);
		});

		setTemplateDefautValue(that.props, meta);
	});
}

//模板修改
function modifierMeta(props, meta) {
	const that = this;
	const { getUrlParam, form, pageConfig } = props;
	//添加复制卡片对话框模板
	this.facardCopy.initCopyCardTemplate(meta);
	//添加参照过滤
	addHeadAreaReferFilter(props, meta, constants.ReferFilterConfig);
	addHeadAreaReferFilter(props, meta, constants.usufructReferFilterConfig);
	addBodyReferFilter(props, meta, constants.ReferFilterConfig);

	//删除本不属于 gridrelation 中的区域
	delete meta['gridrelation'][assetAll];

	let status = getUrlParam('status');

	meta[basicInfoForm].items.map((item) => {
		// 资产类别
		if (item.attrcode === 'pk_category') {
			item.onlyLeafCanSelect = true;
			item.queryCondition = () => {
				let pk_org = form.getFormItemsValue(basicInfoForm, 'pk_org');
				pk_org = pk_org && pk_org.value;
				return {
					pk_org,
					transi_type: that.state.pageCode
				};
			};
		}

		// 管理部门 是否允许选择非末级
		if (item.attrcode === 'pk_mandept' || item.attrcode === 'pk_mandept_v') {
			item.onlyLeafCanSelect = true;
		}
		// 使用部门 是否允许选择非末级
		if (item.attrcode === 'pk_usedept' || item.attrcode === 'pk_usedept_v') {
			item.onlyLeafCanSelect = true;
		}
		//使用状况、增加方式只能选择末级
		if (item.attrcode === 'pk_addreducestyle' || item.attrcode === 'pk_usingstatus') {
			item.onlyLeafCanSelect = true;
		}
	});

	// 隐藏使用权页签，并保持展开状态
	meta[usufructasset_tab].isunfold = true;
	meta[usufructasset_tab].areaVisible = false;

	meta[usufructasset_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'contract_number') {
			item.renderStatus = 'browse';
			item.render = (value, record) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									//获取主键
									let pk = form.getFormItemsValue(basicInfoForm, 'pk_bill_src').value;
									let transi_type_source = form.getFormItemsValue(basicInfoForm, 'transi_type_source')
										.value;
									CardLinkToBill.call(this, props, pk, transi_type_source);
								}}
							>
								{record['contract_number'] && record['contract_number'].value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	meta[financeForm].items.map((item) => {
		// 会计科目
		if (item.attrcode === 'pk_account_subject') {
			item.onlyLeafCanSelect = true;
			item.queryCondition = () => {
				let pk_accbook = form.getFormItemsValue(basicInfoForm, 'pk_accbook');
				pk_accbook = pk_accbook && pk_accbook.value;
				return {
					pk_accountingbook: pk_accbook
				};
			};
		}
		// 建卡当期计提
		if (item.attrcode === 'isdepfornewcard') {
            //录入原始卡片 不应用该元素 newasset_flag === 0
            //固定资产卡片 默认隐藏该元素，由账簿处理器管理显示 newasset_flag === 10
			item.visible = false;
		}
	});

	//附属设备 表体添加操作列
	let oprCol = createOprationColumn(props, {
		tableId: subequip_tab,
		areaId: 'card_body_inner',
		getInnerBtns: (props, text, record, index) => {
			let status = getUrlParam('status');
			if (status === UISTATE.BROWSE) {
				return [];
			} else {
				return Object.values(CARD_BTNS.TABLE_BODY.SUBEQUIP_TAB);
			}
		},
		tableButtonClick: (props, key, text, record, index, tableId) => {
			subequipTab_tableButtonClick(props, key, text, record, index);
		}
	});
	meta[subequip_tab].items.push(oprCol);

	//多使用部门 表体添加操作列
	let oprCol1 = createOprationColumn(props, {
		tableId: usedept_tab,
		areaId: 'card_body_inner1',
		getInnerBtns: (props, text, record, index) => {
			let status = props.getUrlParam('status');
			if (status === UISTATE.BROWSE) {
				return [];
			} else {
				return Object.values(CARD_BTNS.TABLE_BODY.USEDEPT_TAB);
			}
		},
		tableButtonClick: (props, key, text, record, index, tableId) => {
			usedeptTab_tableButtonClick(props, key, text, record, index);
		}
	});
	meta[usedept_tab].items.push(oprCol1);

	//减值记录 bill_code 添加超链
	meta[devalue_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HQ');
								}}
							>
								{record.values.bill_code && record.values.bill_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//调拨记录 bill_code_out（调出单号） 添加超链
	meta[deploy_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code_out') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HC');
								}}
							>
								{record.values.bill_code_out && record.values.bill_code_out.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
		if (item.attrcode == 'bill_code_in') {
			//调入
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill_in.value, 'HD');
								}}
							>
								{record.values.bill_code_in && record.values.bill_code_in.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//评估记录 bill_code（评估单号） 添加超链
	meta[evaluate_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HE');
								}}
							>
								{record.values.bill_code && record.values.bill_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//变动记录 bill_code（变动单号） 添加超链
	meta[alter_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HG');
								}}
							>
								{record.values.bill_code && record.values.bill_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//减少记录 reducesource（减少来源） 添加超链
	meta[reduce_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'reducesource') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(
										that,
										props,
										record.values.pk_bill.value,
										record.values.bill_type.value
									);
								}}
							>
								{record.values.reducesource && record.values.reducesource.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//多使用部门
	meta[usedept_tab].items.map((item, key) => {
		if (item.attrcode == 'pk_dept' || item.attrcode == 'pk_dept_v') {
			item.onlyLeafCanSelect = true;
			item.isMultiSelectedEnabled = true;
		}
	});

	//租赁变更页签的阶梯租金 表体添加操作列
	let oprCol2 = createOprationColumn(props, {
		tableId: lease_change_tab,
		areaId: 'card_body_inner5',
		getInnerBtns: (props, text, record, index) => {
			return Object.values(CARD_BTNS.TABLE_BODY.LEASE_CHANGE_TAB);
		},
		tableButtonClick: (props, key, text, record, index, tableId) => {
			leaseChangeTab_tableButtonClick(props, key, text, record, index);
		}
	});
	meta[lease_change_tab].items.push(oprCol2);

	//阶梯租金标准页签 表体添加操作列
	let oprCol3 = createOprationColumn(props, {
		tableId: steprentstandard_tab,
		areaId: 'card_body_inner2',
		getInnerBtns: (props, text, record, index) => {
			return Object.values(CARD_BTNS.TABLE_BODY.STEPRENTSTANDARD_TAB);
		},
		tableButtonClick: (props, key, text, record, index, tableId) => {
			steprentStandardTab_tableButtonClick(props, key, text, record, index);
		}
	});
	meta[steprentstandard_tab].items.push(oprCol3);

	return meta;
}

//附属设备表体操作列事件
const subequipTab_tableButtonClick = (props, key, text, record, index) => {
	const { cardTable } = props;
	switch (key) {
		case CARD_BTNS.TABLE_BODY.SUBEQUIP_TAB.DELETE_LINE:
			cardTable.delRowsByIndex(subequip_tab, index);
			setBodyBtnsEnable(props, subequip_tab);

			break;
		default:
			break;
	}
};

//多使用部门表体操作列事件
const usedeptTab_tableButtonClick = (props, key, text, record, index) => {
	const { cardTable } = props;
	switch (key) {
		case CARD_BTNS.TABLE_BODY.USEDEPT_TAB.DELETE_LINE:
			cardTable.delRowsByIndex(usedept_tab, index);
			setBodyBtnsEnable(props, usedept_tab);

			break;
		default:
			break;
	}
};

//租赁变更页签表体操作列事件
const leaseChangeTab_tableButtonClick = (props, key, text, record, index) => {
    const { form, editTable } = props;
	switch (key) {
		case CARD_BTNS.TABLE_BODY.LEASE_CHANGE_TAB.DELETE_LINE:
      /* 按阶梯租金计租 */
			let step_lease_flag = form.getFormItemsValue(basicInfoForm, 'step_lease_flag').value;
			if (step_lease_flag === true) {
				if (index === 0) {
					/* 国际化： "201201504A-0000104": "按阶梯租金计租，不允许删除第一行阶梯租金！" */
					showMessage(props, { content: getMultiLangByID('201201504A-0000104'), color: 'warning' });
					return false;
				}
			}
			editTable.deleteTableRowsByIndex(lease_change_tab, index);
			setBodyBtnsEnable(props, lease_change_tab);

			break;
		default:
			break;
	}
};

//阶梯租金标准页签表体操作列事件
const steprentStandardTab_tableButtonClick = (props, key, text, record, index) => {
	switch (key) {
		case CARD_BTNS.TABLE_BODY.STEPRENTSTANDARD_TAB.DELETE_LINE:
			props.cardTable.delRowsByIndex(steprentstandard_tab, index);
			setBodyBtnsEnable(props, steprentstandard_tab);

			break;
		default:
			break;
	}
};

//初始化 state 中的参数
function initState(meta) {
	if (meta[basicInfoForm]) {
		//获取模板上使用部门、管理部门是否可以为空
		let items = meta[basicInfoForm].items;
		for (let i = 0; i < items.length; i++) {
			let item = items[i];
			if (item.attrcode === FIELDS.PK_USEDEPT) {
				this.state.usedeptIsNotNull = !!item.required;
			} else if (item.attrcode === FIELDS.PK_MANDEPT) {
				this.state.mandeptIsNotNull = !!item.required;
			}
		}
	}
}

//将模板默认值设置到界面上
export function setTemplateDefautValue(props, meta) {
	let defaultValue = {
		[basicInfoForm]: {}
	};
	meta[basicInfoForm].items.map((item) => {
		if (item.initialvalue) {
			defaultValue[basicInfoForm][item.attrcode] = item.initialvalue;
		}
	});
	meta[usufructasset_tab].items.map((item) => {
		if (item.initialvalue) {
			defaultValue[basicInfoForm][item.attrcode] = item.initialvalue;
		}
	});
	props.form.setFormItemsValue(basicInfoForm, defaultValue[basicInfoForm]);
}
